package com.my.algorithmlearning.leetcode;

import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName SingleNumber
 * @Description SingleNumber
 * @Author wanghaiwei
 * @Date 2022/11/29 14:44
 */
public class SingleNumber {
    public int singleNumber(int[] nums) {
        Map<Integer, Integer> result = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (result.containsKey(nums[i])) {
                result.remove(nums[i]);
            }else {
                result.put(nums[i], 1);
            }
        }
        return result.entrySet().iterator().next().getKey();
    }

    public int singleNumberXOR(int[] nums) {
        int result = 0;
        for (int i = 0; i < nums.length; i++) {
            result ^= nums[i];
        }
        return result;
    }

    public static void main(String[] args) {
        SingleNumber solution = new SingleNumber();
        Assert.isTrue(1 == solution.singleNumber(new int[]{2,2,1}), "2,2,1计算错误");
        Assert.isTrue(4 == solution.singleNumber(new int[]{4,1,2,1,2}), "4,1,2,1,2计算错误");
        Assert.isTrue(1 == solution.singleNumber(new int[]{1}), "1计算错误");


        Assert.isTrue(1 == solution.singleNumberXOR(new int[]{2,2,1}), "singleNumberXOR2,2,1计算错误");
        Assert.isTrue(4 == solution.singleNumberXOR(new int[]{4,1,2,1,2}), "singleNumberXOR4,1,2,1,2计算错误");
        Assert.isTrue(1 == solution.singleNumberXOR(new int[]{1}), "singleNumberXOR1计算错误");
    }
}
